package com.shop.cloud.common.data.datascope.supplier;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.common.security.entity.BaseUser;
import com.shop.cloud.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author
 * <p>
 * 供应商ID拦截器
 */
@Slf4j
@AllArgsConstructor
public class SupplierIdInterceptor implements InnerInterceptor {

	private final SupplierScopeProperties supplierScopeProperties;

	@Override
	public void beforeQuery(Executor executor, MappedStatement mappedStatement, Object parameter, RowBounds rowBounds,
							  ResultHandler resultHandler, BoundSql boundSql) {
		PluginUtils.MPBoundSql mPBoundSql = PluginUtils.mpBoundSql(boundSql);
		//查询数据权限配置
		List<SupplierScopeMapper> mapperIds = supplierScopeProperties.getMappers();
		Map<String, List<SupplierScopeMapper>> mapScopeMapper =  mapperIds.stream().collect(Collectors.groupingBy(SupplierScopeMapper::getValue));
		String mappedStatementMapper;
		//未配置供应商数据权限，直接放行
		if (mapperIds==null || mapperIds.size()<=0) {
			return;
		}else{
			//com.shop.cloud.mall.admin.mapper.GoodsSpuMapper.selectPage1
			mappedStatementMapper = mappedStatement.getId();
			String[] strs = StrUtil.splitToArray(mappedStatementMapper,".");
			mappedStatementMapper = strs[strs.length-2];
			//没有配置当前mapper，直接放行
			if(!mapScopeMapper.containsKey(mappedStatementMapper)){
				return;
			}
		}

		BaseUser user = SecurityUtils.getUser();
		if (user == null) {
			//没有用户信息，直接放行
			return;
		}
		//非供应商管理员类型账号直接放行
		if(!StrUtil.equals(CommonConstants.USER_TYPE_3, user.getType())){
			return;
		}
		String originalSql = boundSql.getSql();

		String scopeName = mapScopeMapper.get(mappedStatementMapper).get(0).getColumn();
		//获取当前用户的供应商id
		String supplierId = user.getSupplierId();
		String mappedStatementId = mappedStatement.getId();
		//过滤供应商查询
		if(StrUtil.containsAny(mappedStatementId,"selectCount")){
			//count查询过滤
			String w = "";
			if(StrUtil.containsAnyIgnoreCase(originalSql,"where")){
				w = " and ";
			}else{
				w = " where ";
			}
			originalSql = originalSql + w + scopeName + " = '" + supplierId + "'";
		} else if(StrUtil.containsAny(mappedStatementId,"selectPage","selectList")){
			//selectPage、selectList查询过滤
			originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + scopeName + " = '" + supplierId + "'";
		} else{
			//直接放行
			return;
		}
		mPBoundSql.sql(originalSql);
		return;
	}

}
